import { Request, Response } from 'express';
import { userService } from './service';
import { Like, Between, In, Not } from 'typeorm';
import { ApiResponse } from '../../types/page';
import { AuthRequest } from "../../types/auth";
import { UserStatus, AdmissionResult } from '../../entities/User';
import { notificationService } from '../../services/NotificationService';
import { createWxSDK } from '../../sdk/weixin';
import { mpWeixinConfig } from '../../config';

type UserListResponse = {
  records: any[];
  total: number;
  size: number;
  current: number;
  pages: number;
};

/**
 * 获取用户列表
 */
export const getUsers = async (req: AuthRequest, res: Response) => {
  try {
    const current = Number(req.query.page) || 1;
    const size = Number(req.query.size) || 10;
    
    const whereQuery: any = {};

    // 添加查询条件 - 字符串类型参数
    if (req.query.name) {
      whereQuery.name = Like(`%${req.query.name}%`);
    }
    if (req.query.idCard) {
      whereQuery.idCard = String(req.query.idCard);
    }
    if (req.query.mobile) {
      whereQuery.mobile = String(req.query.mobile);
    }
    if (req.query.province) {
      whereQuery.province = String(req.query.province);
    }
    if (req.query.examType) {
      whereQuery.examType = String(req.query.examType);
    }
    if (req.query.examNumber) {
      whereQuery.examNumber = String(req.query.examNumber);
    }
    
    // 添加查询条件 - 数字类型参数
    if (req.query.gender !== undefined) {
      whereQuery.gender = Number(req.query.gender);
    }
    if (req.query.admissionResult !== undefined) {
      whereQuery.admissionResult = Number(req.query.admissionResult);
    }
    if (req.query.admissionBatch !== undefined) {
      whereQuery.admissionBatch = Number(req.query.admissionBatch);
    }
    if (req.query.paymentStatus !== undefined) {
      whereQuery.paymentStatus = Number(req.query.paymentStatus);
    }
    if (req.query.status !== undefined) {
      whereQuery.status = Number(req.query.status);
    }
    if (req.query.subscriptionStatus !== undefined) {
      whereQuery.subscriptionStatus = Number(req.query.subscriptionStatus);
    }
    
    // 分数范围查询
    if (req.query.minScore || req.query.maxScore) {
      whereQuery.score = Between(
        Number(req.query.minScore) || 0,
        Number(req.query.maxScore) || 999
      );
    }

    const { users, total } = await userService.findAll({
      ...whereQuery,
      page: current,
      pageSize: size,
    });
    
    const response: ApiResponse<UserListResponse> = {
      success: true,
      data: {
        records: users,
        total,
        size,
        current,
        pages: Math.ceil(total / size)
      }
    };

    res.json(response);
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取用户列表失败',
      error: error.message
    });
  }
};

/**
 * 获取用户详情
 */
export const getUserDetail = async (req: Request, res: Response) => {
  try {
    const id = req.params.id;

    if (!id) {
      return res.status(400).json({
        success: false,
        message: '用户ID不能为空'
      });
    }

    const { user, payments } = await userService.getUserDetail(id);
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      data: {
        user,
        payments
      }
    });

  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取用户详情失败',
      error: error.message
    });
  }
};


/**
 * 更新用户
 */
export const updateUser = async (req: Request, res: Response) => {
  try {
    const id = req.params.id;
    const userData = req.body;
    
    const user = await userService.update(id, userData);
    
    if (!user) {
      return res.status(404).json({ 
        success: false, 
        message: '用户不存在' 
      });
    }
    
    res.json({ 
      success: true, 
      data: user 
    });
  } catch (error: any) {
    res.status(error.status || 500).json({ 
      success: false, 
      message: error.message || '更新用户失败'
    });
  }
};

/**
 * 禁用用户（禁用用户）
 */
export const disableUser = async (req: AuthRequest, res: Response) => {
  try {
    const id = req.params.id;
    const currentUser = req.user;

    if (!currentUser) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const result = await userService.disableUser(id, currentUser.id);
    
    if (!result) {
      return res.status(404).json({ 
        success: false, 
        message: '用户不存在' 
      });
    }
    
    res.json({ 
      success: true, 
      message: '禁用用户成功' 
    });
  } catch (error: any) {
    res.status(500).json({ 
      success: false, 
      message: '禁用用户失败', 
      error: error.message 
    });
  }
};

/**
 * 更新录取状态（通过/拒绝录取）
 */
export const updateAdmissionStatus = async (req: Request, res: Response) => {
  try {
    const id = req.params.id;
    const { admissionResult, admittedMajor, admissionBatch, admissionNoticePhoto } = req.body;
    
    if (admissionResult === undefined) {
      return res.status(400).json({
        success: false,
        message: '录取结果不能为空'
      });
    }
    
    // 如果是录取通过，需要校验专业、批次和录取通知书
    if (Number(admissionResult) === AdmissionResult.ADMITTED) {
      if (!admittedMajor) {
        return res.status(400).json({
          success: false,
          message: '录取专业不能为空'
        });
      }
      
      if (!admissionBatch) {
        return res.status(400).json({
          success: false,
          message: '录取批次不能为空'
        });
      }
      
      if (!admissionNoticePhoto) {
        return res.status(400).json({
          success: false,
          message: '录取通知书照片不能为空'
        });
      }
      
      // 调用通过录取的服务
      const result = await userService.admitUser(id, {
        admittedMajor,
        admissionBatch,
        admissionResult: AdmissionResult.ADMITTED,
        admissionTime: new Date(),
        admissionNoticePhoto
      });
      
      if (!result) {
        return res.status(404).json({
          success: false,
          message: '用户不存在'
        });
      }
      
     
      
      return res.json({
        success: true,
        message: '录取成功'
      });
    } else {
      // 如果是拒绝录取，直接更新录取结果
      const result = await userService.updateAdmissionResult(id, Number(admissionResult));
      
      if (!result) {
        return res.status(404).json({
          success: false,
          message: '用户不存在'
        });
      }
      
      // 拒绝录取也需要发送通知
      try {
        // 获取用户信息
        const user = await userService.findById(id);
        if (user && user.wxOpenid && user.subscriptionStatus) {
          // 使用事件名称、申请人和申请时间发送订阅消息
          await sendAdmissionSubscriptionMessage(
            user, 
            '录取结果通知', 
            '很遗憾，您未被录取。如有疑问，请联系招生办。'
          );
        }
      } catch (notificationError) {
        console.error('发送拒绝录取通知时出错:', notificationError);
        // 继续执行，不影响主流程
      }
      
      return res.json({
        success: true,
        message: '操作成功'
      });
    }
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '操作失败',
      error: error.message
    });
  }
};

/**
 * 发送录取结果订阅消息
 * @param user 用户
 * @param eventName 事件名称
 * @param remark 备注信息
 */
async function sendAdmissionSubscriptionMessage(user: any, eventName: string, remark: string): Promise<boolean> {
  try {
    // 检查用户是否订阅了消息
    if (!user.subscriptionStatus) {
      console.log(`用户 ${user.name}（ID: ${user.id}）未订阅消息，跳过小程序消息发送`);
      return false;
    }

    // 检查用户是否有微信openId
    if (!user.wxOpenid) {
      console.log(`用户 ${user.name}（ID: ${user.id}）没有关联的微信openId，无法发送小程序消息`);
      return false;
    }

    // 使用SDK发送订阅消息
    const wxSDK = createWxSDK(mpWeixinConfig);
    
    // 打印当前使用的 appid
    console.log('发送录取结果订阅消息，使用的 appid:', mpWeixinConfig.appId);
    
    // 构建消息数据
    const messageData = {
      openid: user.wxOpenid,
      templateId: 'UlDZFFWn7Bv8Nqe7VBOUzMoXi7gmnl-yeHSOqbZkRuI',
      page: 'pages/enrollment/admission', // 跳转到录取结果页面
      data: {
        thing1: {
          value: eventName
        },
        thing4: {
          value: user.name || '未知用户'
        },
        time6: {
          value: new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          })
        }
      }
    };

    // 发送订阅消息
    const result = await wxSDK.templateMsg.send(messageData);
    
    if (result) {
      console.log(`成功发送录取结果订阅消息给用户 ${user.name}（ID: ${user.id}）`);
      return true;
    } else {
      console.error(`发送录取结果订阅消息失败`);
      return false;
    }
  } catch (error) {
    console.error('发送录取结果订阅消息时出错:', error);
    return false;
  }
}

/**
 * 导出用户列表
 */
export const exportUsers = async (req: Request, res: Response) => {
  try {
    // 支持查询条件导出
    const whereQuery: any = {};
    
    // 添加查询条件 - 字符串类型参数
    if (req.query.name) {
      whereQuery.name = Like(`%${req.query.name}%`);
    }
    if (req.query.idCard) {
      whereQuery.idCard = String(req.query.idCard);
    }
    if (req.query.mobile) {
      whereQuery.mobile = String(req.query.mobile);
    }
    if (req.query.province) {
      whereQuery.province = String(req.query.province);
    }
    if (req.query.examType) {
      whereQuery.examType = String(req.query.examType);
    }
    if (req.query.examNumber) {
      whereQuery.examNumber = String(req.query.examNumber);
    }
    
    // 添加查询条件 - 数字类型参数
    if (req.query.gender !== undefined) {
      whereQuery.gender = Number(req.query.gender);
    }
    if (req.query.admissionResult !== undefined) {
      whereQuery.admissionResult = Number(req.query.admissionResult);
    }
    if (req.query.admissionBatch !== undefined) {
      whereQuery.admissionBatch = Number(req.query.admissionBatch);
    }
    if (req.query.paymentStatus !== undefined) {
      whereQuery.paymentStatus = Number(req.query.paymentStatus);
    }
    if (req.query.status !== undefined) {
      whereQuery.status = Number(req.query.status);
    }
    
    // 分数范围查询
    if (req.query.minScore || req.query.maxScore) {
      whereQuery.score = Between(
        Number(req.query.minScore) || 0,
        Number(req.query.maxScore) || 999
      );
    }
    
    const buffer = await userService.exportUsers(whereQuery);
    
    // 设置响应头
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    
    // 使用encodeURIComponent对中文文件名进行编码
    const fileName = encodeURIComponent('用户列表.xlsx');
    res.setHeader('Content-Disposition', `attachment; filename="${fileName}"; filename*=UTF-8''${fileName}`);
    
    // 发送Excel文件
    res.send(buffer);
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '导出失败',
      error: error.message
    });
  }
};

/**
 * 更新缴费状态
 */
export const updatePaymentStatus = async (req: Request, res: Response) => {
  try {
    const id = req.params.id;
    const { paymentStatus } = req.body;
    
    if (paymentStatus === undefined) {
      return res.status(400).json({
        success: false,
        message: '缴费状态不能为空'
      });
    }
    
    const result = await userService.updatePaymentStatus(id, paymentStatus);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    res.json({
      success: true,
      message: '更新缴费状态成功'
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '更新缴费状态失败',
      error: error.message
    });
  }
};

/**
 * 更新用户的系统用户标记
 * 仅管理员可以操作
 */
export const updateSystemUserStatus = async (req: AuthRequest, res: Response) => {
  try {
    const id = req.params.id;
    const { isSystem } = req.body;
    const currentUser = req.user;

    if (!currentUser) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    if (isSystem === undefined) {
      return res.status(400).json({
        success: false,
        message: '系统用户标记不能为空'
      });
    }

    // 更新用户的系统用户标记
    const user = await userService.update(id, { 
      isSystem: isSystem ? 1 : 0,
      updatedBy: currentUser.id
    });
    
    if (!user) {
      return res.status(404).json({ 
        success: false, 
        message: '用户不存在' 
      });
    }
    
    res.json({ 
      success: true, 
      message: `已${isSystem ? '设置' : '取消'}系统用户标记`,
      data: {
        id: user.id,
        isSystem: user.isSystem,
        isSystemText: user.isSystemText
      }
    });
  } catch (error: any) {
    res.status(error.status || 500).json({ 
      success: false, 
      message: error.message || '更新系统用户标记失败'
    });
  }
}; 